import random
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from verifications import constants
from meiduo_mall.libs.yuntongxun.yuntongxun.sms import CCP

# Create your views here.

# 获取日至器
import logging
logger = logging.getLogger('django')


# GET /sms_codes/(?P<mobile>1[3-9]\d{9})
class SMSCodeView(APIView):
    def get(self, request, mobile):
        """
        获取短信验证码
        1. 随机生成6位的数字作为短信验证码
        2. 在redis存储短信验证码内容.以'sms_<mobile>'为key, 以验证码为value
        3. 使用云通讯给'mobile'发送短信
        4. 返回应答短信发送成功
        """
        # 0.判断'mobile'60s内是否发送过短信
        redis_conn = get_redis_connection('verify_codes')

        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            # 60s内给'mobile'发送过短信
            return Response({"message": "请求次数过于频繁"}, status=status.HTTP_400_BAD_REQUEST)


        # 1.随机生成6位的数字作为短信验证码
        sms_code = "%06d" % random.randint(0, 999999)
        logger.info('短信验证码为:　%s' % sms_code)
        # 2. 在redis存储短信验证码内容.以'sms_<mobile>'为key, 以验证码为value
        # redis_conn.set('<key>', '<value>', '<expires>')
        # redis_conn.setex('<key>','<expires>', '<value>')

        # 创建redis管道对象
        pl = redis_conn.pipeline()

        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)

        # 一次性执行管道中所有的命令
        pl.execute()

        # 3. 使用云通讯给'mobile'发送短信
        expires = constants.SMS_CODE_REDIS_EXPIRES // 60

        # 发送短信任务消息
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code, expires)

        # 4. 返回应答,短信发送成功
        return Response({'message': 'OK'})
